<template>
    <el-scrollbar id="scrollbar" ref="scrollbarRef" @scroll="listenScroll">
        <!-- 骨架屏 -->
        <div v-show="isLoading" class="p-4">
            <ElSkeleton animated :rows="20" class="pdf-skeleton" />
        </div>

        <!-- 预览失败 -->
        <div v-show="isErrors" class="flex flex-col justify-center items-center h-full">
            <div class="text-tx-regular mb-4">
                加载文件失败，请尝试刷新页面
            </div>
            <ElButton type="primary" @click="emits('refresh')">点击刷新</ElButton>
        </div>

        <!-- 预览成功 -->
        <div v-if="!isErrors" class="pdf-container" :style="{'opacity': isLoading ? '0' : '1'}">
            <div
                class="spacer"
                :style="{
                    height: totalHeight + (totalPages * 10) + 'px'
                }"
            ></div>
            <div
                v-for="page in visiblePages"
                :id="'page-container-' + page"
                :key="page"
                :style="pageStyleObj(page)"
                class="page inline-block"
            >
                <canvas :id="'page-' + page" class="page-canvas"></canvas>
                <div
                    :id="'text-layer-' + page"
                    class="text-layer-container"
                    :style="{ height: pageHeight + 'px' }"
                ></div>
            </div>

        </div>
    </el-scrollbar>
</template>

<script setup lang="ts">
import 'pdfjs-dist/web/pdf_viewer.css'
import { ElScrollbar } from 'element-plus'

defineProps<{
    isErrors: boolean;
    isLoading: boolean;
    totalPages: number;
    pageHeight: number;
    totalHeight: number;
    visiblePages: number[];
    listenScroll: any;
    pageStyleObj: any;
}>()

const emits = defineEmits<{
    (e: 'refresh'): void
    (e: 'scroll', scrollTop: number): void
}>()

const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()

defineExpose({
    setScrollTop: (n: number) => {
        scrollbarRef.value!.setScrollTop(n)
    }
})
</script>

<style scoped lang="scss">
:deep(.el-scrollbar__view) {
    height: 100%;
    padding: 3px 15px 15px;
}

.pdf-container {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    .page-canvas {
        box-shadow: 0 0 12px 0 rgb(78 89 105 / 15%);
    }
    :deep(.textLayer) {
        display: flex;
        justify-content: center;
        width: auto !important;
        height: auto !important;
    }
    .text-layer-container {
        position: absolute;
        top: 50%;
        right: 0;
        left: 50%;
        display: flex;
        justify-content: center;
        transform: translate(-50%, -50%);
    }
}
</style>
